package libnetdb.dm.assoc.dhp.demo;

import java.io.*;
import java.util.*;

import libnetdb.dm.assoc.base.*;
import libnetdb.dm.assoc.util.*;


/**
 * This class implements the ARInput interface so that it can
 * be treated as the input of the DHPMiner. It reads from text
 * file and treat each line as an itemset (i.e., transaction).
 * Each item is seperated by [comma], [space], or [tab].
 *
 * @author Cheng-Ru Lin
 * @version 1.0
 */
public class TextInput implements ARInput {
    private BufferedReader br = null;
    private String filename;
    private NameSpace ns;
    private Itemset itemset = null;

    public TextInput(String filename, NameSpace ns) {
        this.filename = filename;
        this.ns = ns;
    }
    
    public void open(){
    }
    
    public void close() throws IOException{
        if(br != null) br.close();
        br = null;        
    }

    private Itemset moveNext() throws IOException{
        String line;
        while((line = br.readLine())!=null){
            StringTokenizer st = new StringTokenizer(line," \t,");
            int ids[] = new int[st.countTokens()];
            for(int i=0;i<ids.length;++i)
                ids[i] = ns.registerName(st.nextToken());
            if(ids.length > 0) return new Itemset(ids);
        }
        return null;
    }

    public void beforeFirst() throws IOException {
        if(br != null) br.close();
        br = new BufferedReader(new FileReader(filename));
        itemset = moveNext();
    }

    public Itemset next() throws IOException {
        Itemset rc = itemset;
        itemset = moveNext();
        return rc;
    }

    public boolean hasNext() {
        return itemset != null;
    }
}